package com.gmail.hongyz.myfuse.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.gmail.hongyz.myfuse.common.PageObject;
import com.gmail.hongyz.myfuse.dao.BaseDao;

public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {

	public List queryForPage(final String hql, final int start, final int limit) {
		return (List) getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = session.createQuery(hql);
				if (start >= 0) {
					query.setFirstResult(start);
				}
				if (limit > 0) {
					query.setMaxResults(limit);
				}
				return query.list();
			}
		});
	}
	
	public List queryForPage(final String hql, final PageObject pageObject) {
		int total = pageObject.getTotal();
		if (total == -1) {
			total = getHibernateTemplate().find(hql).size();
			pageObject.setTotal(total);
		}
		return (List) getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
				Query query = session.createQuery(hql);
				if (pageObject.getStart() >= 0) {
					query.setFirstResult(pageObject.getStart());
				}
				if (pageObject.getLimit() > 0) {
					query.setMaxResults(pageObject.getLimit());
				}
				return query.list();
			}
		});
	}

	public Object load(Class entityClass, Serializable id) {
		return getHibernateTemplate().load(entityClass, id);
	}

	public Serializable save(Object entity) {
		return getHibernateTemplate().save(entity);
	}

	public void update(Object entity) {
		getHibernateTemplate().update(entity);
	}
	
	public void delete(Object entity) {
		getHibernateTemplate().delete(entity);
	}

}
